﻿//*** Guidance generated code ***//
using System.Linq;
using System.Diagnostics.Contracts;
using System.Collections.Generic;
using System;

using ProjectBase.Core;
using ProjectBase.Core.Web;
using ProjectBase.Mvc;

using Survey.Common;

namespace Survey.Filters.Restrictions
{
    public class ControlRenderProvider : IControlRenderProvider
    {
        IDictionary<Type, IControlRenderHandler> _handlers;

        public void ControlHtml_OnPreRenderControl(IVisualControl control, PreRenderControlEventArgs args)
        {
            // default implementation checks the EntityController
            var controller = args.ViewContext.Controller as IWebController<IEntityModel<IPersistentObject, IFilter>>;
            if (controller.IsNull() || control.IsNull())
            {
                return;
            }

            // is there handler for this type
            IControlRenderHandler handler;
            var entityType = controller.Model.GetType()
                .GetInterface("IEntityModel`2")
                .GetGenericArguments()
                .First();

            if (!Handlers.TryGetValue(entityType, out handler))
            {
                return;
            }

            handler.Handle(control, args);

        }
        public virtual void Add(Type type, IControlRenderHandler handler)
        {
            if (Handlers.ContainsKey(type))
            {
                return;
            }
            Handlers[type] = handler;
        }
        protected virtual IDictionary<Type, IControlRenderHandler> Handlers
        {
            get { return _handlers ?? (_handlers = new Dictionary<Type, IControlRenderHandler>()); }
            set { _handlers = value; }
        }
    }
}